package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.VO.CartVo;
import com.example.demo.dao.CartDao;
import com.example.demo.dao.OrderDao;
import com.example.demo.model.Customer;
import com.example.demo.model.OrderItem;
import com.example.demo.model.corder;
import com.example.demo.service.CartService;
import com.example.demo.service.CustomerService;
import com.example.demo.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class Orderimpl extends ServiceImpl<OrderDao, corder> implements OrderService {

    @Resource
    CustomerService customerService;
    @Resource
    CartService cartService;
    @Resource
    OrderDao orderDao;


    public class InsertException extends Exception{
        String message;
        public InsertException(String x) {
            this.message=x;
            System.out.println(message);
        }

    }

    @Override
    public corder create(Integer uid) throws InsertException {
        List<CartVo> list = cartService.getVOByUid(uid);
        //计算总价
        Long totalPrice = 0L;
        //创建订单详细项的信息
        for (CartVo cartVO : list) {
            totalPrice += (cartVO.getPrice()*cartVO.getAmount());
        }
        //Address address = addressService.getByAid(aid,uid);
        Customer customer=customerService.getCustomer(uid);
        corder order = new corder();
        order.setUid(uid);
        //收货地址数据
        order.setRecvName(customer.getName());
        order.setRecvPhone(customer.getTelephone());
        order.setRecvAddress(customer.getAddress());
        //支付、总价
        order.setStatus(0);
        order.setTotalPrice(totalPrice);
        order.setOrderTime(new Date(System.currentTimeMillis()));


        //查询数据
        Integer rows = orderDao.insertOrder(order);
        if(rows != 1) {
            throw new InsertException("插入时异常");
        }

        //创建订单详细项的信息
        for (CartVo cartVO : list) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOid(order.getOid());
            orderItem.setPid(cartVO.getPid());
            orderItem.setTitle(cartVO.getPname());
            orderItem.setImg(cartVO.getImg());
            orderItem.setPrice(cartVO.getPrice());
            orderItem.setNum(cartVO.getAmount());
            //插入数据
            rows = orderDao.insertOrderItem(orderItem);
            if(rows != 1) {
                throw new InsertException("插入时异常");
            }
        }
        return order;
    }
}
